from django.contrib import admin
from .models import (
    VoiceCommand, CommandTemplate, NLPProcessingLog, 
    DeviceAlias, ActionAlias, ConversationContext
)


@admin.register(VoiceCommand)
class VoiceCommandAdmin(admin.ModelAdmin):
    """语音命令管理"""
    list_display = ['user', 'original_text_short', 'command_type', 'confidence', 'is_executed', 'created_at']
    list_filter = ['command_type', 'language', 'is_executed', 'created_at']
    search_fields = ['user__username', 'original_text', 'intent']
    ordering = ['-created_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'original_text', 'processed_text', 'language')
        }),
        ('识别结果', {
            'fields': ('command_type', 'intent', 'entities', 'confidence')
        }),
        ('执行状态', {
            'fields': ('is_executed', 'execution_result'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at']
    
    def original_text_short(self, obj):
        """显示原始文本的简短版本"""
        return obj.original_text[:50] + '...' if len(obj.original_text) > 50 else obj.original_text
    original_text_short.short_description = '原始文本'


@admin.register(CommandTemplate)
class CommandTemplateAdmin(admin.ModelAdmin):
    """命令模板管理"""
    list_display = ['name', 'intent', 'command_type', 'priority', 'is_active', 'created_at']
    list_filter = ['command_type', 'is_active', 'created_at']
    search_fields = ['name', 'intent', 'pattern']
    ordering = ['-priority', 'name']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'intent', 'command_type', 'is_active', 'priority')
        }),
        ('模式配置', {
            'fields': ('pattern', 'entity_mapping')
        }),
        ('响应配置', {
            'fields': ('response_template',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at', 'updated_at']


@admin.register(NLPProcessingLog)
class NLPProcessingLogAdmin(admin.ModelAdmin):
    """NLP处理日志管理"""
    list_display = ['voice_command_id', 'processing_step', 'status', 'processing_time', 'created_at']
    list_filter = ['status', 'processing_step', 'created_at']
    search_fields = ['voice_command__original_text', 'processing_step']
    ordering = ['-created_at']
    
    fieldsets = (
        ('处理信息', {
            'fields': ('voice_command', 'processing_step', 'status', 'processing_time')
        }),
        ('数据详情', {
            'fields': ('input_data', 'output_data'),
            'classes': ('collapse',)
        }),
        ('错误信息', {
            'fields': ('error_message',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at']
    
    def has_add_permission(self, request):
        """禁止手动添加处理日志"""
        return False
    
    def voice_command_id(self, obj):
        """显示语音命令ID"""
        return obj.voice_command.id
    voice_command_id.short_description = '语音命令ID'


@admin.register(DeviceAlias)
class DeviceAliasAdmin(admin.ModelAdmin):
    """设备别名管理"""
    list_display = ['device', 'alias', 'language', 'is_active', 'created_by', 'created_at']
    list_filter = ['language', 'is_active', 'created_at']
    search_fields = ['device__name', 'alias']
    ordering = ['device', 'alias']
    
    fieldsets = (
        ('别名信息', {
            'fields': ('device', 'alias', 'language', 'is_active')
        }),
        ('创建信息', {
            'fields': ('created_by', 'created_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at']
    
    def save_model(self, request, obj, form, change):
        """保存时自动设置创建者"""
        if not change:  # 新建时
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(ActionAlias)
class ActionAliasAdmin(admin.ModelAdmin):
    """动作别名管理"""
    list_display = ['get_action_display', 'alias', 'language', 'device_type', 'is_active', 'created_at']
    list_filter = ['action', 'language', 'device_type', 'is_active', 'created_at']
    search_fields = ['alias']
    ordering = ['action', 'alias']
    
    fieldsets = (
        ('别名信息', {
            'fields': ('action', 'alias', 'language', 'is_active')
        }),
        ('适用范围', {
            'fields': ('device_type',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at']


@admin.register(ConversationContext)
class ConversationContextAdmin(admin.ModelAdmin):
    """对话上下文管理"""
    list_display = ['user', 'session_id', 'conversation_state', 'last_intent', 'expires_at', 'created_at']
    list_filter = ['conversation_state', 'created_at']
    search_fields = ['user__username', 'session_id', 'last_intent']
    ordering = ['-updated_at']
    
    fieldsets = (
        ('会话信息', {
            'fields': ('user', 'session_id', 'conversation_state')
        }),
        ('上下文数据', {
            'fields': ('context_data', 'last_intent', 'last_entities'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('expires_at', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at', 'updated_at']
    
    def get_queryset(self, request):
        """只显示未过期的上下文"""
        from django.utils import timezone
        return super().get_queryset(request).filter(expires_at__gt=timezone.now())
